package com.mls.wms.android.widget.inwh;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.http.RequestManager;
import com.google.zxing.client.android.Intents;
import com.mls.wms.android.R;
import com.mls.wms.android.constant.ScanTypeConstants;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.model.DirectMoveQtyModel;
import com.mls.wms.android.model.ResponseResult;
import com.mls.wms.android.util.ViewUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-09-14.
 */
public class DirectMoveActivity extends BaseActivity {
    private long fromLocationId = 0L;
    private long toLocationId = 0L;
    private long skuId = 0L;
    private int movableQty = 0;

    private EditText etCartonNo = null;
    private EditText etFromLocationNo = null;
    private EditText etScanBarcode = null;
    private EditText etInventoryStatus = null;
    private EditText etItemName = null;
    private EditText etMovableQty = null;
    private EditText etToLocationNo = null;
    private EditText etMoveQty = null;

    private Button btnContinue = null;
    private EditText selectEt = null;
    private AnimDialogFragment progressDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_direct_move);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        this.etCartonNo = (EditText) this.findViewById(R.id.act_direct_move_txt_carton_no);
        this.etFromLocationNo = (EditText) this.findViewById(R.id.act_direct_move_txt_from_location_no);
        this.etScanBarcode = (EditText) this.findViewById(R.id.act_direct_move_txt_scan_barcode);
        this.etInventoryStatus = (EditText) this.findViewById(R.id.act_direct_move_txt_inventory_status);
        this.etItemName = (EditText) this.findViewById(R.id.act_direct_move_txt_spec_item_name);
        this.etMovableQty = (EditText) this.findViewById(R.id.act_direct_move_txt_movable_qty);
        this.etToLocationNo = (EditText) this.findViewById(R.id.act_direct_move_txt_to_location_no);
        this.etMoveQty = (EditText) this.findViewById(R.id.act_direct_move_txt_move_qty);
        this.etMoveQty.setText("1");

        this.btnContinue = (Button) this.findViewById(R.id.act_direct_move_btn_continue);


        //文本框事件
        List<EditText> ets = ViewUtils.getDescendants(this, EditText.class, false);
        for (final EditText item : ets) {
            if (item.isEnabled() == true && item.getVisibility() == View.VISIBLE) {
                item.setSelectAllOnFocus(true);//获取焦点全选
                item.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                            return onEnterDownEditText(v);
                        }

                        return false;
                    }
                });
                item.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            return onEnterDownEditText(v);
                        }
                        return false;
                    }
                });

                item.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (true == hasFocus) {
                            selectEt = item;
                        }
                    }
                });
            }
        }

        //按钮事件
        this.btnContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doSubmit();
            }
        });

    }

    /**
     * 按下回车
     *
     * @param view
     * @return
     */
    private boolean onEnterDownEditText(View view) {
        if (view.getId() == this.etCartonNo.getId()) {
            GetAvailableQty(1);
            return true;
        } else if (view.getId() == this.etFromLocationNo.getId()) {
            isValidFromLocation();
            return true;
        } else if (view.getId() == this.etScanBarcode.getId()) {
            GetAvailableQty(2);
            return true;
        } else if (view.getId() == this.etToLocationNo.getId()) {
            isValidToLocation();
            return true;
        } else if (view.getId() == this.etMoveQty.getId()) {
            isValidMoveQty();
            return true;
        }

        return false;
    }

    private void GetAvailableQty(int type) {
        if (type == 1 && true == TextUtils.isEmpty(this.etCartonNo.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_carton_no_not_null), this.etCartonNo);
        } else if (type == 2 && this.fromLocationId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_from_location_no_not_null), this.etFromLocationNo);
        } else if (type == 2 && true == TextUtils.isEmpty(this.etScanBarcode.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_item_barcode_not_null), this.etScanBarcode);
        } else {
            Map<String, String> data = new HashMap<String, String>();
            data.put("locationId", this.fromLocationId + "");
            data.put("barcode", this.etScanBarcode.getText().toString().trim());
            data.put("cartonNo", this.etCartonNo.getText().toString().trim());

            String url = ServicePort.getUrl(ServicePort.DirectMoveQty).replace("{restfulid0}", this.fromLocationId + "").replace("{restfulid1}", this.etScanBarcode.getText().toString().trim());

            get(url, data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            DirectMoveQtyModel model = new DirectMoveQtyModel();
                            model = model.parseJson(result.getResult());

                            skuId = model.getSkuId();
                            etScanBarcode.setText(model.getBarcode());
                            etItemName.setText(model.getItemName());
                            etInventoryStatus.setText(model.getInventoryStatusName());
                            etMovableQty.setText(model.getAvailableQty() + "");
                            movableQty = model.getAvailableQty();

                            etToLocationNo.requestFocus();
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, selectEt);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, selectEt);
                }
            }, 1);
        }
    }

    private void isValidFromLocation() {
        if (true == TextUtils.isEmpty(this.etFromLocationNo.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_from_location_no_not_null), etFromLocationNo);
        } else {
            Map<String, String> data = new HashMap<String, String>();
            data.put("locationNo", this.etFromLocationNo.getText().toString().trim());
            get(ServicePort.getUrl(ServicePort.DirectMoveFromLocation), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            fromLocationId = Long.parseLong(result.getResult());

                            etScanBarcode.requestFocus();
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, etFromLocationNo);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, etFromLocationNo);
                }
            }, 1);
        }
    }

    private void isValidToLocation() {
        if (true == TextUtils.isEmpty(this.etToLocationNo.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_to_location_no_not_null), etToLocationNo);
        } else {
            String url = ServicePort.getUrl(ServicePort.DirectMoveToLocation).replace("{restfulid0}", this.etToLocationNo.getText().toString().trim());
            get(url, null, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            toLocationId = Long.parseLong(result.getResult());

                            etMoveQty.requestFocus();
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, etToLocationNo);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, etToLocationNo);
                }
            }, 1);
        }
    }


    private void isValidMoveQty() {
        if (TextUtils.isEmpty(this.etMoveQty.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_move_qty_not_null), etMoveQty);
        } else {
            int moveQty = Integer.parseInt(this.etMoveQty.getText().toString().trim());
            if (moveQty <= 0) {
                showDialog(getResources().getString(R.string.dialog_msg_move_qty_smaller), etMoveQty);
            } else if (moveQty > this.movableQty) {
                showDialog(getResources().getString(R.string.dialog_msg_move_qty_bigger), etMoveQty);
            } else {
                doSubmit();
            }
        }
    }

    private boolean checkSubmit() {
        if (this.fromLocationId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_from_location_no_not_null), this.etFromLocationNo);
            return false;
        } else if (this.skuId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_item_barcode_not_null), this.etScanBarcode);
            return false;
        } else if (this.toLocationId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_to_location_no_not_null), this.etToLocationNo);
            return false;
        } else if (TextUtils.isEmpty(this.etMoveQty.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_move_qty_not_null), etMoveQty);
        } else {
            int moveQty = Integer.parseInt(this.etMoveQty.getText().toString().trim());
            if (moveQty <= 0) {
                showDialog(getResources().getString(R.string.dialog_msg_move_qty_smaller), this.etMoveQty);
                return false;
            } else if (moveQty > this.movableQty) {
                showDialog(getResources().getString(R.string.dialog_msg_move_qty_bigger), this.etMoveQty);
                return false;
            } else {
                //
            }
        }


        return true;
    }


    private void doSubmit() {
        if (true == this.checkSubmit()) {
            progressDialog.show(getFragmentManager(), this.toString());
            JSONObject data = null;
            try {
                data = new JSONObject();
                data.put("locationId", this.fromLocationId);
                data.put("toLocationId", this.toLocationId);
                data.put("skuId", this.skuId);
                data.put("cartonNo", this.etCartonNo.getText().toString().trim());
                data.put("qty", this.etMoveQty.getText().toString().trim());
            } catch (Exception e) {
                e.printStackTrace();
            }
            post(ServicePort.getUrl(ServicePort.DirectMoveInsert), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            toLocationId = 0L;
                            skuId = 0L;
                            movableQty = 0;

                            etCartonNo.setText("");
                            etScanBarcode.setText("");
                            etInventoryStatus.setText("");
                            etItemName.setText("");
                            etMovableQty.setText("");
                            etToLocationNo.setText("");
                            etMoveQty.setText("1");

                            if (false == TextUtils.isEmpty(etCartonNo.getText().toString().toString())) {
                                //整箱操作
                                fromLocationId = 0L;
                                etFromLocationNo.setText("");

                                etCartonNo.requestFocus();
                            } else {
                                etScanBarcode.requestFocus();
                            }
                            progressDialog.dismiss();
                            return;
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        progressDialog.dismiss();
                        showDialog(errorMsg, etMoveQty);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    progressDialog.dismiss();
                    showDialog(s, etMoveQty);
                }
            }, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (this.selectEt != null) {
            switch (requestCode) {
                case ScanTypeConstants.SCAN_BAR_CODE:
                    if (resultCode == RESULT_OK) {
                        Bundle bundle = data.getExtras();
                        this.selectEt.setText(bundle.getString(Intents.Scan.RESULT, ""));
                        this.selectEt.requestFocus();
                        onEnterDownEditText(this.selectEt);
                    }
                default:
                    break;
            }
        }
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_text_direct_move;
    }
}
